/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.exam;

import java.io.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Project: javase - Ex4
 * <p>Powered by webrx On 2021-12-14 19:19:42
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Ex4 {
    public static void main(String[] args) {
        //String f = "C:\\javase\\09io\\src\\cn\\exam\\Ex4.java";
        //copyText(new File(f), new File("c:/source.txt"));
        print(new File("D:\\jdk\\jdk-17.0.1\\lib\\src"));
    }

    public static void copyText(File src, File dst) {
        try (var a = new BufferedReader(new FileReader(src)); var b = new BufferedWriter(new FileWriter(dst, true))) {
            b.write(String.format("文件：%s[%03d行]%n", src.getName(), getFileRows(src)));
            b.write(String.format("-".repeat(55)).concat("\r\n"));
            AtomicInteger num = new AtomicInteger(1);
            a.lines().forEach((s) -> {
                try {
                    b.write(String.format("%02d、%s\r\n", num.getAndIncrement(), s));
                    System.out.println(s);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            });
            b.write("\r\n");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void print(File file) {
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                if (f.isDirectory()) {
                    print(f);
                } else {
                    if (f.getName().toLowerCase().endsWith(".java")) copyText(f, new File("c:/jdk17.txt"));
                }
            }
        } else {
            if (file.getName().toLowerCase().endsWith(".java")) copyText(file, new File("c:/s.txt"));
        }
    }

    public static long getFileRows(File file) {
        long rows = 0;
        try (var b = new BufferedReader(new FileReader(file))) {
            rows = b.lines().count();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rows;
    }
}
